package com.website.dayouziblog.exception;

import com.website.dayouziblog.response.BaseResponse;
import com.website.dayouziblog.response.RespGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 自定义全局异常处理类(所有的异常都会被拦截到这里)
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    //日志
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    //处理自定义异常
    @ExceptionHandler(value = BaseException.class)
    public BaseResponse<Object> baseExceptionHandler(BaseException e){
        logger.error("发生业务异常！原因是：" + e.getMessage());
        return RespGenerator.returnError(e.getCode(), e.getMessage());
    }

    //处理空指针异常
    @ExceptionHandler(value = NullPointerException.class)
    public BaseResponse<Object> exceptionHandler(NullPointerException e){
        logger.error("发生空指针异常！原因是：" + e);
        e.printStackTrace();
        return RespGenerator.returnError(BaseErrorEnum.BODY_NOT_MATCH);
    }

    //处理其他异常
    @ExceptionHandler(value = Exception.class)
    public BaseResponse<Object> exceptionHandler(Exception e){
        logger.error("未知异常！原因是：" + e);
        e.printStackTrace();
        return RespGenerator.returnError(BaseErrorEnum.INTERNAL_SERVER_ERROR);
    }


}
